using System;
using System.Data;
using System.Configuration;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using TanashCMS.Business;
using TanashCMS.Business.DTO;
using NHibernate;
using System.IO;

public partial class manager_pages_Default : CMSManagementPageBase
{
    private enum ViewMode
    {
        Grid,
        List
    }

    private ViewMode mViewMode { get { return ViewState["viewmode"] != null ? (ViewMode)ViewState["viewmode"] : ViewMode.Grid; } set { ViewState["viewmode"] = value; } }

    protected void Page_Load(object sender, EventArgs e)
    {
    }

    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

        if (!IsPostBack)
        {
            List<ListItem> items = GetTemplates();
            foreach(ListItem item in items)
                ddlAction.Items.Add(item);

            ddlAction.Items[0].Attributes.Add("disabled", "true");
            ddlAction.Items[5].Attributes.Add("disabled", "true");
        }
    }

    protected override void Render(HtmlTextWriter writer)
    {
        if (mViewMode == ViewMode.Grid)
        {
            btnViewGrid.Enabled = false;
            btnList.Enabled = true;
        }
        else
        {
            btnViewGrid.Enabled = true;
            btnList.Enabled = false;
        }
        base.Render(writer);
    }

    /*protected void btnCreateNewPage_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/manager/pages/create.aspx");
    }*/
    protected void dlWebPages_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        if (mWebsite == null)
            return;

        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            WebPage webpage = (WebPage)e.Item.DataItem; 
            Image imgPage = (Image)e.Item.FindControl("imgPage");
            HtmlGenericControl rowcontainer = (HtmlGenericControl)e.Item.FindControl("rowcontainer");

            if (webpage != null)
            {
                if (mWebsite.HomePageID == webpage.ID)
                    imgPage.ImageUrl = "~/manager/images/HomePage.gif";
                if (webpage.State == CMSObjectState.Shallow)
                    rowcontainer.Attributes.CssStyle.Add(HtmlTextWriterStyle.BackgroundColor, "yellow");
            }

            HyperLink linkPreview = (HyperLink)e.Item.FindControl("linkPreview");
            linkPreview.NavigateUrl = "http://" + mWebsite.HostHeader + Request.ApplicationPath.TrimEnd('/') + "/preview.aspx?guid=" + ((int)TanashCMS.Business.CMSObjectType.WebPage).ToString().PadLeft(2, '0') + webpage.GUID;

            HyperLink linkAddress = (HyperLink)e.Item.FindControl("linkAddress");
            linkAddress.Text = "http://" + mWebsite.HostHeader + Request.ApplicationPath.TrimEnd('/') + "/?guid=" + ((int)TanashCMS.Business.CMSObjectType.WebPage).ToString().PadLeft(2, '0') + webpage.GUID; ;
        }

    }
    protected void btnList_Click(object sender, EventArgs e)
    {
        foreach (DataListItem listItem in dlWebPages.Items)
        {
            if (listItem.ItemType == ListItemType.Item
                || listItem.ItemType == ListItemType.AlternatingItem)
            {
                Image imgPage = (Image)listItem.FindControl("imgPage");
                HtmlGenericControl row = (HtmlGenericControl)listItem.FindControl("rowcontainer");
                HtmlGenericControl header = (HtmlGenericControl)listItem.FindControl("rowheader");
                HtmlGenericControl details = (HtmlGenericControl)listItem.FindControl("rowdetails");
                HtmlGenericControl address = (HtmlGenericControl)listItem.FindControl("rowaddress");

                imgPage.Style["display"] = "none";
                row.Attributes["class"] = "webpage_list_row";
                header.Attributes["class"] = "webpage_list_rowheader";
                details.Attributes["class"] = "webpage_list_pagedetails";
                address.Attributes["class"] = "webpage_list_pageurl";
            }
        }
        mViewMode = ViewMode.List;
    }
    protected void btnViewGrid_Click(object sender, EventArgs e)
    {
        foreach (DataListItem listItem in dlWebPages.Items)
        {
            if (listItem.ItemType == ListItemType.Item
                || listItem.ItemType == ListItemType.AlternatingItem)
            {
                Image imgPage = (Image)listItem.FindControl("imgPage");
                HtmlGenericControl row = (HtmlGenericControl)listItem.FindControl("rowcontainer");
                HtmlGenericControl header = (HtmlGenericControl)listItem.FindControl("rowheader");
                HtmlGenericControl details = (HtmlGenericControl)listItem.FindControl("rowdetails");
                HtmlGenericControl address = (HtmlGenericControl)listItem.FindControl("rowaddress");

                imgPage.Style["display"] = "block";
                row.Attributes["class"] = "webpage_grid_row";
                header.Attributes["class"] = "webpage_grid_rowheader";
                details.Attributes["class"] = "webpage_grid_pagedetails";
                address.Attributes["class"] = "webpage_grid_pageurl";
            }

        }
        mViewMode = ViewMode.Grid;
    }
    protected void ddlAction_SelectedIndexChanged(object sender, EventArgs e)
    {
        switch (ddlAction.SelectedValue)
        {
            case "delete":
                DeleteSelectedPages();
                break;
            case "sethomepage":
                SetHomePage();
                break;
            case "publish":
                SetSelectedPagesState(CMSObjectState.Published);
                break;
            case "unpublish":
                SetSelectedPagesState(CMSObjectState.Shallow);
                break;
            case "secure":
                SetSelectedPagesSecurity(true);
                break;
            case "public":
                SetSelectedPagesSecurity(false);
                break;
            default:
                SetTemplate();
                break;

        }

        ddlAction.SelectedIndex = 0;
    }

    private void SetTemplate()
    {
        ISession session = Configuration.GetCurrentSession();
        ITransaction tx = session.BeginTransaction();

        try
        {
            foreach (int pageID in getSelectedPageIDs())
            {
                WebPage page = session.Get<WebPage>(pageID);
                if (Path.GetExtension(ddlAction.SelectedValue) == ".xsl")
                {
                    page.TemplateType = PageTemplateType.XSLT;
                }
                else
                    page.TemplateType = PageTemplateType.MasterPage;
                page.MasterPage = ddlAction.SelectedValue;
                session.Save(page);
            }

            mWebsite.NeedsPublish = true;
            session.SaveOrUpdate(mWebsite);
            CMSMasterPage.setPublishLinkVisibility(true);

            tx.Commit();
            session.Flush();
            session.Disconnect();

            DataBind();

            ShowSystemFeedback("The page templates have been set");
        }
        catch (Exception ex)
        {
            tx.Rollback();
            session.Disconnect();
            CMSMasterPage.SystemFeedback = "Error deleting page:<Br/>";
            CMSMasterPage.SystemFeedback += ex.Message;
            while (ex.InnerException != null)
            {
                ex = ex.InnerException;
                CMSMasterPage.SystemFeedback += "<br/>" + ex.Message;
            }

            // TODO: until logging is implemented
            throw ex;
        }
    }

    private int[] getSelectedPageIDs()
    {
        List<int> selectedIDs = new List<int>();
        foreach (DataListItem item in dlWebPages.Items)
        {
            CheckBox chkSelected = (CheckBox)item.FindControl("chkWebPage");
            Literal litPageID = (Literal)item.FindControl("litPageID");
            if (chkSelected != null && litPageID != null)
            {
                if (chkSelected.Checked)
                    selectedIDs.Add(int.Parse(litPageID.Text));
            }
        }

        return selectedIDs.ToArray();        
    }

    private void DeleteSelectedPages()
    {
        ISession session = Configuration.GetCurrentSession();
        ITransaction tx = session.BeginTransaction();

        try
        {
            foreach (int pageID in getSelectedPageIDs())
            {
                WebPage page = session.Get<WebPage>(pageID);
                session.Delete(page);
            }

            mWebsite.NeedsPublish = true;
            session.SaveOrUpdate(mWebsite);
            CMSMasterPage.setPublishLinkVisibility(true);

            tx.Commit();
            session.Flush();
            session.Disconnect();

            DataBind();
        }
        catch (Exception ex)
        {
            tx.Rollback();
            session.Disconnect();
            CMSMasterPage.SystemFeedback = "Error deleting page:<Br/>";
            CMSMasterPage.SystemFeedback += ex.Message;
            while (ex.InnerException != null)
            {
                ex = ex.InnerException;
                CMSMasterPage.SystemFeedback += "<br/>" + ex.Message;
            }
        }
    }

    private void SetSelectedPagesState(CMSObjectState newState)
    {
        ISession session = Configuration.GetCurrentSession();
        ITransaction tx = session.BeginTransaction();

        try
        {
            foreach (int pageID in getSelectedPageIDs())
            {
                WebPage page = session.Get<WebPage>(pageID);
                page.State = newState;
                session.SaveOrUpdate(page);
            }

            mWebsite.NeedsPublish = true;
            session.SaveOrUpdate(mWebsite);
            CMSMasterPage.setPublishLinkVisibility(true);

            tx.Commit();
            session.Flush();
            session.Disconnect();

            DataBind();
        }
        catch (Exception ex)
        {
            tx.Rollback();
            session.Disconnect();
            CMSMasterPage.SystemFeedback = "Error deleting page:<Br/>";
            CMSMasterPage.SystemFeedback += ex.Message;
            while (ex.InnerException != null)
            {
                ex = ex.InnerException;
                CMSMasterPage.SystemFeedback += "<br/>" + ex.Message;
            }
        }
    }

    private void SetSelectedPagesSecurity(bool isSecure)
    {
        ISession session = Configuration.GetCurrentSession();
        ITransaction tx = session.BeginTransaction();

        try
        {
            foreach (int pageID in getSelectedPageIDs())
            {
                WebPage page = session.Get<WebPage>(pageID);
                page.IsSecure = isSecure;
                session.SaveOrUpdate(page);
            }

            mWebsite.NeedsPublish = true;
            session.SaveOrUpdate(mWebsite);
            CMSMasterPage.setPublishLinkVisibility(true);

            tx.Commit();
            session.Flush();
            session.Disconnect();

            DataBind();
        }
        catch (Exception ex)
        {
            tx.Rollback();
            session.Disconnect();
            CMSMasterPage.SystemFeedback = "Error deleting page:<Br/>";
            CMSMasterPage.SystemFeedback += ex.Message;
            while (ex.InnerException != null)
            {
                ex = ex.InnerException;
                CMSMasterPage.SystemFeedback += "<br/>" + ex.Message;
            }
        }
    }

    private void SetHomePage()
    {
        int selectedID = 0;
        ISession session = Configuration.GetCurrentSession();
        ITransaction tx = session.BeginTransaction();

        int[] pageIDs = getSelectedPageIDs();

        if (pageIDs.Length > 1)
        {
            CMSMasterPage.SystemFeedback = "Please select only one page to set as the home page";
            return;
        }
        else if (pageIDs.Length == 0)
        {
            CMSMasterPage.SystemFeedback = "Please select a page";
            return;
        }

        selectedID = pageIDs[0];

        try
        {
            WebPage page = session.Get<WebPage>(selectedID);
            mWebsite.HomePageID = page.ID;
            session.Update(mWebsite);

            mWebsite.NeedsPublish = true;
            session.SaveOrUpdate(mWebsite);
            CMSMasterPage.setPublishLinkVisibility(true);

            tx.Commit();
            session.Flush();
            session.Disconnect();

            DataBind();
        }
        catch (Exception ex)
        {
            tx.Rollback();
            session.Disconnect();
            CMSMasterPage.SystemFeedback = "Error deleting page:<Br/>";
            CMSMasterPage.SystemFeedback += ex.Message;
            while (ex.InnerException != null)
            {
                ex = ex.InnerException;
                CMSMasterPage.SystemFeedback += "<br/>" + ex.Message;
            }
        }
    }

    protected void btnCreateNewPage_Click(object sender, EventArgs e)
    {
        ISession session = Configuration.GetCurrentSession();
        ITransaction tx = session.BeginTransaction();

        int pageid = 0;
        WebPage newPage = new WebPage();
        newPage.Website = mWebsite;
        newPage.Title = txtPageTitle.Text;
        newPage.State = CMSObjectState.Published;
        newPage.ObjectType = CMSObjectType.WebPage;
        newPage.PageType = WebPageType.Standard;
        newPage.MasterPage = "default";
        newPage.GUID = Guid.NewGuid().ToString();

        try
        {
            session.Save(newPage);

            mWebsite.NeedsPublish = true;
            session.SaveOrUpdate(mWebsite);
            CMSMasterPage.setPublishLinkVisibility(true);

            session.Flush();
            tx.Commit();
            pageid = newPage.ID;
            session.Disconnect();
        }
        catch (Exception ex)
        {
            tx.Rollback();
            session.Disconnect();
            ShowSystemFeedback(ex.Message);
            return;
        }
        Response.Redirect("Build.aspx?id=" + pageid.ToString());
    }

    private List<ListItem> GetTemplates()
    {
        List<ListItem> items = new List<ListItem>();

        WebpageTemplate[] templates = mWebsite.GetTemplates();
        foreach (WebpageTemplate template in templates)
        {
            items.Add(new ListItem(template.TemplateName, template.TemplateName));
        }

        return items;

        // load master page list
        /*
        DirectoryInfo dir = new DirectoryInfo(Server.MapPath(Request.ApplicationPath.TrimEnd('/') + "/MasterPages/" + mWebsite.SubFolderName + "/"));

        if (dir.Exists)
        {
            FileInfo[] masterFiles = new FileInfo[0];
            try
            {
                masterFiles = dir.GetFiles("*.master");
            }
            catch (Exception ex)
            {
            }



            foreach (FileInfo masterFile in masterFiles)
                items.Add(new ListItem(Path.GetFileNameWithoutExtension(masterFile.Name), Request.ApplicationPath.TrimEnd('/') + "/xsl/templates/" + mWebsite.SubFolderName + "/" + masterFile.Name));
        }*/

        // and the xslt template list if applicable
        /*dir = new DirectoryInfo(Server.MapPath(Request.ApplicationPath.TrimEnd('/') + "/xsl/templates/" + mWebsite.SubFolderName + "/"));
        if (dir.Exists)
        {
            FileInfo[] xslTemplates = new FileInfo[0];
            try
            {
                xslTemplates = dir.GetFiles("*.xsl");
            }
            catch (Exception ex)
            {
            }
            foreach (FileInfo xslTemplate in xslTemplates)
            {
                if (!xslTemplate.Name.Contains("_temp"))
                    items.Add(new ListItem(Path.GetFileNameWithoutExtension(xslTemplate.Name), Request.ApplicationPath.TrimEnd('/') + "/xsl/templates/" + mWebsite.SubFolderName + "/" + xslTemplate.Name));
            }
        }*/

        return items;
    }
}
